/*
 * @Author: chengsl
 * @Date: 2021-12-21 14:33:18
 * @LastEditors: chengsl
 * @LastEditTime: 2023-04-28 10:12:10
 * @Description: request发请求疯装
 */
import axios from 'axios'
// import router from '@/router/routers'
// import store from '../store'
const { encode } = require('js-base64')
import { Encrypt, Decrypt } from '@/utils/AES' // 加密解密
import unifiedTip from '@/utils/unifiedTip'// 全局统一提示
const { Notification, Message } = unifiedTip
import router from '../router'
// 创建axios实例
const service = axios.create({
  timeout: 10000 // 请求超时时间
})

/**
 * 将参数对象改造成url字符串返回
 * @param {*} obj
 * @returns str
 */
function requestBodyToUrl(obj) {
  let str = '?'
  const keys = Object.keys(obj)
  for (let i = 0; i < keys.length; i++) {
    const key = keys[i]
    const value = obj[key]
    str = `${str}${key}=${value}${i === keys.length - 1 ? '' : '&'}`
  }
  return str
}
// request拦截器
service.interceptors.request.use(
  config => {
    try {
      if (config.inUrl) { // 参数在URL里面
        const params = (typeof config.data === 'object') ? config.data
          : (typeof config.data === 'string')
            ? JSON.parse(config.data) : {}
        if (params && Object.keys(params).length) {
          config.url += requestBodyToUrl(params)
          config.data = undefined
        }
      }
    } catch (error) {
      console.log('error11--', error)
    }
		if(config.reqEncryption) { // 需要加密
			config.headers.reqEncryption = true
			const sm4Data = JSON.parse(JSON.stringify(config.data || {}))
			config.data = {
				'dataSecret': Encrypt(sm4Data)
			}
			console.log(Decrypt(config.data.dataSecret), '解密后的数据')
		}
    config.headers['Content-Type'] = config.headers['Content-Type'] || 'application/json'
    const TOKEN = localStorage.getItem('token')
		if (TOKEN) {
			config.headers.Authorization = 'Bearer ' + TOKEN
		} else {
			config.headers.Authorization = 'Basic ' + encode('clientId:clent_secret')
		}
    return config
  },
  error => {
    console.log(error)
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    const code = response.status
		let message = '接口请求失败'
		try {
			message = response.data.message
		} catch (error) {
			//
		}
		// console.log('response---', response)
    if (code < 200 || code > 300) {
      Notification.error({
        title: response.message
      })
      return Promise.reject('error')
    } else {
			if(response.config.headers.reqEncryption && response.data.data) { // 对需要加密解密的接口 加解密
        response.data['data'] = Decrypt(JSON.parse(JSON.stringify(response.data.data))['dataSecret'])
			}
      if (response.data.code === 200 && response.data.status === 200) { // TODO 和后端商量下 是否只有200代表接口成功
				// console.log('解密-----', response.data['data'])
        return response.data
      } else {
        Message.warning(message || '接口请求失败')
        return Promise.reject(response.data)
      }
    }
  },
  error => {
		// let code = 0;
		// console.log(code, '-', status,'error.response----', error.response)
		let message = ''
		try {
			const code = error.response.data.code
			const status = error.response.data.status
			message = error.response.data.message
			if (error.toString().indexOf('Error: timeout') !== -1) {
				Notification.error({
					title: '网络请求超时',
					duration: 2000
				})
				return Promise.reject(error)
			} else if(code === 401 && status === 401){
				Notification.error({
					title: message || 'token认证失败',
					duration: 2000
				})
				router.push('/login')
			} else {
				Notification.error({
					title: message || '接口请求失败',
					duration: 2000
				})
			}
		} catch (error) {
			Notification.error({
				title: message || '接口请求失败',
				duration: 2000
			})
		}
    return Promise.reject(error)
  }
)
export default service
